package options

import (
	"fmt"

	"github.com/mars/internal/pkg/utils"
	"github.com/spf13/pflag"
)

type WxCloudOptions struct {
	AppId     string `mapstructure:"app-id"     json:"app-id"`
	AppSecret string `mapstructure:"app-secret" json:"app-secret"`
	EnvId     string `mapstructure:"env-id"     json:"env-id"` // 微信云环境ID
}

func NewWxCloudOptions() *WxCloudOptions {
	return &WxCloudOptions{
		AppId:     "",
		AppSecret: "",
		EnvId:     "",
	}
}

func (o *WxCloudOptions) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&o.AppId, "wxcloud.app-id", o.AppId, "Specify the wxcloud app id.")
	fs.StringVar(&o.AppSecret, "wxcloud.app-secret", o.AppSecret, "Specify the wxcloud app secret.")
	fs.StringVar(&o.EnvId, "wxcloud.env-id", o.EnvId, "Specify the wxcloud environment id.")
}

func (o *WxCloudOptions) Validate() []error {
	var errs = []error{}
	if o.AppId == "" {
		errs = append(errs, fmt.Errorf("wxcloud.app-id is required"))
	}
	if o.AppSecret == "" {
		errs = append(errs, fmt.Errorf("wxcloud.app-secret is required"))
	}
	if o.EnvId == "" {
		errs = append(errs, fmt.Errorf("wxcloud.env-id is required"))
	}

	if len(o.AppSecret) > 0 {
		clear, err := utils.Decrypt(o.AppSecret)
		if err != nil {
			errs = append(errs, err)
		}
		o.AppSecret = clear
	}

	return errs
}
